/**
 * 内置模块
 */

// import inquirer from "inquirer";
const { promisify } = require("util"); //node用具库, promisify函数
const path = require("path");

/**
 * 第三方库
 */
//download-git-repo 库 不支持promise的，使用 promisify函数 可实现promise
const download = promisify(require("download-git-repo")); //下载模块库
const open = require("open");
const inquirer = require("inquirer");
const chalk = require("chalk");

/**
 * 自己创建的js文件
 */
const {
  vueRepo,
  repoList,
  technicalOptions,
} = require("../config/repo-config.js");
const { commandeSpawn } = require("../utils/terminal.js");
const { compile, writeToFile } = require("../utils/utils.js");

/**
 * 创建项目的action
 * @param {*} project 项目名称 比如：vue create demo。指的就是demo
 * @param {*} others 存放项目名称后面的跟着的参数列表，是个数组
 */
const createProjectAction = async (project, others) => {
  // console.log(project);
  // console.log(others);
  // download().then(res => {}).catch(err => {})
  // const inquirerParams = [
  //   {
  //     name: "action",
  //     type: "list",
  //     message: "choice create preject type",
  //     choices: [
  //       { name: "vue2", value: "vue2" },
  //       { name: "vue3", value: "vue3" },
  //     ],
  //   },
  // ];
  // console.log("====", );

  let inquirerData = await inquirer.prompt(technicalOptions);
  // console.log("===111", inquirerData.action);
  const result = repoList.find((ele) => ele.value === inquirerData.action);
  if (!result) {
    console.log("No corresponding template found");
    return;
  }

  //1、clone项目模板
  await download(result.url, project, { clone: true });
  // console.log(chalk.rgb(32, 128, 240)("  installing dependencies !")); // 蓝色
  // chalk.blue("Installing dependencies !");

  //2、执行npm install
  //Mac、Linux操作系统的电脑执行npm 内部就是执行npm。Windows系统执行npm 其实是执行了npm.cmd这个命令 platform
  const command = process.platform === "win32" ? "npm.cmd" : "npm";
  chalk.blue("installing dependencies......");
  await commandeSpawn(command, ["install"], { cwd: `./${project}` });

  // 提示用户 cd ${project}
  // 然后再 执行 npm dev
  console.log("");
  console.log(
    "  Successfully created project " + chalk.rgb(240, 160, 32)(`${project}`)
  );
  console.log("  Get started with the following commands");
  console.log("");
  console.log(chalk.rgb(32, 128, 240)(`  cd ${project}`));
  console.log(chalk.rgb(32, 128, 240)(`  npm run dev`));

  //3、运行npm run serve
  // //为了要打开浏览器 这里不用 await，否则会阻塞
  // commandeSpawn(command, ["run", "serve"], {cwd: `./${project}`});

  // //4、打开浏览器
  // //使用第三方库 open
  // open('http://localhost:8080/');
};

/**
 * 添加组件action
 * @param {*} name 组件名字
 * @param {*} targetpath 目标(组件)路径，有默认值
 */
const addVueCpnAction = async (name, targetpath) => {
  //1、编译ejs模块 result (拿到模板内容)
  let result = await compile("vue-component.ejs", {
    name,
    lowerName: name.toLowerCase(),
  });
  // console.log(result);

  //2、将内容写入文件操作   比如： xxx/xxx/src/com/Nav.vue
  const filePath = path.resolve(targetpath, `${name}.vue`); //得到要创建的文件的路劲
  writeToFile(filePath, result); //在com目录下创建Nav.vue文件，然后再写入模板内容
};

/**
 * 添加组件和路由
 * @param {*} name 页面名字, home  则会创建home目录, 在home目录下创建home.vue文件
 * @param {*} targetpath
 */
const addPageAndRouterAction = async (name, targetpath) => {
  //编译ejs模板
  let pageResult = await compile("vue-component.ejs", {
    name,
    lowerName: name.toLowerCase(),
  });
  let routerResult = await compile("vue-router.ejs", {
    name,
    lowerName: name.toLowerCase(),
  });

  //写入文件
  const pagePath = path.resolve(targetpath, `${name}.vue`);
  const routerPath = path.resolve(targetpath, `router.js`);
  writeToFile(pagePath, pageResult);
  writeToFile(routerPath, routerResult);
};

module.exports = {
  createProjectAction,
  addVueCpnAction,
  addPageAndRouterAction,
};
